<template>
	<view class="header">
		<view class="abs-box flex-col">
			<image class="img" src="@/static/images/coupon_center.png"></image>
			<view class="text">天天来领券，优惠看得见</view>
		</view>
	</view>

	<view class="content">
		<view style="padding-top: 20rpx;">
			<view style="width: 90%;margin: 0 auto;"> <u-search placeholder="请输入加油站名称" v-model="keyword" bg-color="#fff"
					@search="search" @custom="search"></u-search>
			</view>
		</view>
		<view class="body">
				<scroll-view scroll-y style="height: 70vh;" @scrolltolower="loadMore">
					<view class="listNull" v-if="couponList.length == 0">
						<img src="@/static/images/listNull.png" alt="" />
						<text>暂无优惠券</text>
					</view>
				<view class="card-item" v-for="(item,index) in couponList" :key="index" @click="goCoupon(item)">
					<!-- 有效期内则显示 -->
					<view class="card" v-if="+new Date(item.endTime)>+new Date()">
						<view class="one flex-between">
							<u-text size="17" bold lines="1" :text="item.stationInfo.name"></u-text>
							<view class="address flex">
								<u-icon name="coupon" size="22" color="#e63305"></u-icon>
								<view class="ml5">
									<u-text :text="item.ctype" size="16" color="#e63305"></u-text>
								</view>
							</view>
						</view>
						<view class="two mt5">
							<u-text size="12" lines="1" type="info" :text="item.name"></u-text>
						</view>
						<view class="three ">
							<view class="left flex-center">
								<text style="font-size: 18px;" v-if="item.ctype=='满减券'">{{'满'+item.fullAmount+'减'+item.amount}}</text>
								<text style="font-size: 18px;" v-else-if="item.ctype=='折扣券'">{{item.cardDisc}}折</text>
								<text style="font-size: 18px;" v-else>￥{{item.amount}}元</text>
							</view>
							<view class="right">
								<image src="@/static/images/coupon-r.png" style="100%"></image>
								<view class="text ">
									<view>
										<view class="title" v-if="item.ctype=='抵扣券'">无门槛抵扣</view>
										<view class="title" v-else-if="item.ctype=='折扣券'">无门槛折扣</view>
										<view class="title" v-else>满{{item.fullAmount}}元可用</view>
										<view class="mt5 flex sub-title">
											<view class="item">
												<!-- 30天内有效 -->
												<!-- {{(+new Date('2025-04-28 00:00:00')-+new Date(item.startTime))/(24*60*60*1000)}} -->
												有效期至：{{item.endTime.split(' ')[0]}}
											</view>
											<!-- <view class="item">
												限本站使用
											</view> -->
										</view>
									</view>
									<image src="@/static/images/coupon-r-2.png"
										style="width: 80rpx;height: 80rpx;margin-left: 30rpx;"></image>
								</view>
							</view>
						</view>

					</view>
				</view>
			<!-- 加载状态 -->
			<u-loadmore :status="loadingState" icon-type="circle" />
			</scroll-view>
			<!-- 分页控件 -->
			<u-pagination v-model="page" :page-count="pageCount" :total="pageTotal" mode="button" @change="pageChange" />
		</view>
	</view>
	<TabBar :tabValue="1" />
</template>

<script setup>
	import API from "@/api/index.js"
	import TabBar from "@/components/tabbar/index.vue"
	import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
	import {
		onLoad,
		onShow,
		onPageScroll,
		onReachBottom,
		onShareAppMessage
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref,computed
	} from "vue"
	import {
		DropdownList
	} from "./data.js";

	onShow(async () => {
		uni.hideTabBar()
	})
	onLoad(async (options) => {
		getList(1)
	})
	// 计算总页数
	const pageCount = computed(() => {
		return Math.ceil(pageTotal.value / pageSize.value)
	})
	let page = ref(1)
	let pageSize = ref(10)
	let pageTotal = ref(10)
	let loadingState = ref('loadmore')
	const menuList = ref(DropdownList)
	const keyword = ref('')
	let couponList = reactive([])

	//请求参数
	const params = ref({});
	let condition = reactive([{
		"filedIndex": "state",
		"filedValue": "true"
	},{
		"filedIndex": "audit",
		"filedValue": "true"
	}])
	const getList = async (pageIndex) => {
		// 处理中condition中为null的数据
		const conditionArray = condition.filter(item => item !== null);
		try{
			loadingState.value = 'loading'
			let res = await API.couponList({
				"pageIndex": pageIndex,
				"pageSize": 10,
				"condition":  conditionArray
			})
			if (pageIndex == 1) {
				couponList.length=0
				Object.assign(couponList, res.data.list)
			} else {
				// couponList = [...couponList, ...res.data.list]
				couponList.push(...res.data.list)
			}
			console.log("couponList res", res.data.list, couponList);
			pageTotal.value = res.data.total
			page.value = res.data.currentPage
			loadingState.value = couponList.length >= pageTotal.value ? 'nomore' : 'loadmore'
		}catch(e){
			loadingState.value = 'error'
		}
	}
	// 搜索
	const search = async (value) => {
		console.log("搜索值", value);
		// 去除空格字符
		let val = value.replace(/\s/g, "")
		if (val == '' || val == null) {
			// uni.showToast({
			// 	title: '请输入正确加油站名称！',
			// 	icon: 'none'
			// })
			condition[2] = {
				"filedIndex": "name",
				"filedValue": null
			}
		} else {
			couponList.length = 0
			condition[2] = {
				"filedIndex": "name",
				"filedValue": value
			}
		}
		getList(1)
	}
	// 领取优惠券
	const goCoupon = async (item) => {
		console.log("优惠券信息", item);
		if(item.isVip&& uni.getStorageSync('userInfo').gradeInfo.name.indexOf("vip")!=-1){
			// vip才可领取优惠券
			let {data} = await API.QUserCoupon(uni.getStorageSync('userInfo').id,item.id)
			if(data){
				// 是否可再次领取优惠券
				let id = await API.uuid()
				let userInfo = uni.getStorageSync('userInfo')
				let res = await API.UserCoupon({
					// 后台修改信息 必要字段------------------
					Id: id.data,
					RegisterUserId: userInfo.id,
					RegisterDeptId: userInfo.deptId,
					RegisteTime: userInfo.registeTime,
					editUserId:userInfo.id,
					EditTime:  +new Date(),
					UserId: userInfo.id,
					// ---------------------------
					// id: item.id,
					id: '',
					CouponId: item.id,
					"expiredate":item.endTime,
					"startTime":item.startTime,
					"endTime":item.endTime,
					"name": item.name,
					"ctype": item.ctype,
					"state": 0,
					"cardDisc": item.cardDisc,
					"fullAmount": item.fullAmount,
					"stationId": item.stationId,
				})
				console.log("领取优惠券 res", res);
				if (res.code == 1) {
					keyword.value=''
					getList(1)
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: "您已经领取过一次了！",
						icon: 'none'
					})
				}
			}else{
				uni.showToast({
					title:'您已经领取过一次了，请使用后再领取！',
					icon:"none"
				})
			}
		}else{
			uni.showToast({
				title:'会员等级不足！不可领取！',
				icon:"none"
			})
		}

	}
	// 页码变化
	const pageChange = (page) => {
		page.value = page
		console.log("页码变化了", page.value);
		getList(page.value)
	}
	// 加载更多（滚动到底部）
	const loadMore = () => {
		console.log("滚动到底了");
		console.log(page.value, pageCount.value);
		if (page.value < pageCount.value) {
			page.value++
			setTimeout(() => {
				getList(page.value)
			}, 1000)
		}
	}
	// 单项筛选
	const onConfirm = (data, id) => {
		console.log("data,id", data, id);
		// bySort.value = data.value
		// fileds=[]
		// fileds.splice(0, fileds.length);
		// if(id==0){
		// 	// 排序方式
		// 	getList(1,data.value)
		// }else if(id==1){
		// 	// 规格选择
		// 	fileds.push({"filedIndex": "spec","filedValue": data.children[0].value})
		// 	getList(1,0,fileds)
		// }else{
		// 	// 品牌选择
		// 	fileds.push({"filedIndex": "brandn","filedValue": data.children[0].value})
		// 	getList(1,0,fileds)
		// }
		// console.log("fileds",fileds);
	}
	// 列表数据
	const mescroll = ref(null);

	const mescrollInit = (mescrollInstance) => {
		mescroll.value = mescrollInstance;
	};

	// 下拉加载回调
	const downCallback = async (mescroll) => {
		try {
			// const res = await getList(1)
			getList(1)
			mescroll.endSuccess()
		} catch (err) {
			uni.showToast({
				title: '刷新失败' + err.message,
				icon: 'none'
			})
			mescroll.endErr() // 必须调用结束方法
		}
	};
	//上拉刷新回调
	const upCallback = async (mescroll) => {
		try {
			// 如果是第一页需手动制空列表
			if (mescroll.num === 1) couponList.value = []
			console.log("couponList upCallback ", couponList);
			getList(mescroll.num);
			mescroll.endSuccess(10)
			console.log("成功了");
			// nextTick(()=>{
			// 	mescroll.endSuccess(couponList.length)
			// })
			// orderList.value = orderList.value.concat(curPageData); //追加新数据
			// mescroll.endBySize(curPageData.length, res.data.total);
		} catch (err) {
			mescroll.endErr();
			console.log("失败了");
		}
	};
</script>

<style lang="scss">
	.listNull {
		display: flex;
		flex-direction: column;
		text-align: center;
		margin: 0 auto;

		image {
			width: 200rpx;
			height: 200rpx;
			// margin: 10% 0 10% 10%;
			margin: 20rpx auto;
		}

		text {
			color: #919ea9;
		}
	}

	.header {
		position: relative;
		height: 340rpx;
		background: url('@/static/images/get_coupon_bg.png') no-repeat center center / 100% 100%,
			linear-gradient(90deg, #FF7931 0%, #e93323 100%);

		.abs-box {
			width: 145px;
			position: absolute;
			left: 26px;
			bottom: 44px;

			.img {
				width: 101px;
				height: 25px;
			}

			.text {
				color: #fff;
				line-height: 18px;
				font-size: 13px;
				padding-top: 11px;
			}
		}

		.nav {
			color: #fff;
			text-align: center;
		}
	}

	.content {
		top: -24px;
		width: 100%;
		position: relative;
		border-top-left-radius: 22px;
		border-top-right-radius: 22px;
		background-color: #f5f5f5;

		.body {
			padding: 0 11px;

			.card-item {
				position: relative;
				margin-top: 20rpx;

				.card {
					// background-image: radial-gradient(circle at 276px top, #f5f5f5, #f5f5f5 5px, transparent 6px), radial-gradient(circle at 276px bottom, #f5f5f5, #f5f5f5 5px, transparent 6px);
					position: relative;
					padding: 20rpx;
					border-radius: 13px;
					background-color: #fff;


					.address {
						background-color: #FAFAFA;
						padding: 10rpx 16rpx;
						font-size: 12px;
						border-radius: 20px;
						font-weight: 800;
					}

					.three {
						margin-top: 20rpx;
						background: $u-primary;
						position: relative;
						height: 150rpx;
						border-radius: 25rpx;
						display: flex;
						align-items: center;

						.left {
							height: 85%;
							width: 250rpx;
							background: url('@/static/images/coupon-l.png');
							background-size: cover;
							font-size: 30px;
							font-weight: 800;
							color: #DC2B2A;
						}

						.right {
							position: absolute;
							right: 0;
							height: 100%;
							width: 470rpx;

							image {
								width: 100%;
								height: 100%;
							}

							.text {
								position: absolute;
								top: 0;
								width: 100%;
								height: 100%;
								text-align: center;
								display: flex;
								align-items: center;
								justify-content: center;
							}

							.title {
								font-size: 16px;
								font-weight: 600;
								color: #fff;
							}

							.sub-title {
								.item {
									font-size: 12px;
									padding: 0 10rpx;
									color: #fff;

									&~.item {
										position: relative;

										&:before {
											content: '';
											position: absolute;
											width: 1rpx;
											height: 22rpx;
											top: 55%;
											margin-top: -12rpx;
											background-color: #fff;
											left: 0;
										}
									}
								}
							}
						}



					}

					.four {}
				}
			}

		}
	}
</style>